using System;
using System.Net;
using System.Threading;
using UnityEngine;

public class PingController : MonoBehaviour, ISocketProcess
{
    Thread m_PingThread;

    PingResultCollection m_PingResultCollection = new PingResultCollection();
    public PingResultCollection pingResultCollection => m_PingResultCollection;
    
    private ClientSocket m_ClientSocket;

    private Func<bool> m_CanPing;
    
    public void Init(ClientSocket clientSocket,Func<bool> canPing = null)
    {
        m_ClientSocket = clientSocket;
        //m_ClientSocket.socketProcess = this;
        //m_ClientSocket.SetReceiveHandler(OnReceiveData);
        transform.SetParent(clientSocket.transform);

        m_CanPing = canPing;
    }

    private void OnReceiveData(byte[] arg1, EndPoint point)
    {
        GameDebug.Log($"OnReceiveData");
    }

    private void Start()
    {
        if (m_PingThread != null)
            m_PingThread.Abort();

        //m_PingThread = new Thread(PingThread);
        //m_PingThread.Start();

        DontDestroyOnLoad(gameObject);
        
    }

    private void OnDestroy()
    {
        
    }

    void Update()
    {
        if (Time.frameCount % 60 == 0)
        {
            Thread.Sleep(1000);

            if (m_ClientSocket == null)
            {
                return;
            }

            if (!m_ClientSocket.connected)
            {
                return;
            }

            if (m_CanPing != null && !m_CanPing())
            {
                GameDebug.LogShowy("Cant Ping");
                return;
            }

            Request_Ping requestBasePing = new Request_Ping();
            requestBasePing.pingData = new PingRequest();
            requestBasePing.pingData.clientSendTime = CommonFunctions.GetTimeStamp();
            requestBasePing.clientSocket = m_ClientSocket;
            //requestBasePing.onResponse = (data) =>
            //{
            //    GameDebug.LogShowy($"Ping onResponse:{Time.time}");
            //};
            requestBasePing.Send();
        }
    }

    public void OnConnect()
    {

    }

    public void OnRequestSend(RequestBase requestBase)
    {

    }

    public void OnReceive(MessagePacket messagePacket)
    {
        GameDebug.Log($"OnReceive:{messagePacket.key}");
    }

    public void OnReConnect()
    {

    }

    public void OnDisconnect()
    {
        throw new NotImplementedException();
    }
}